package cn.zhaoyuening.zshop4j.search.dao.impl;

import cn.zhaoyuening.zshop4j.common.bean.SearchItemBean;
import cn.zhaoyuening.zshop4j.common.bean.SearchResult;
import cn.zhaoyuening.zshop4j.search.dao.SearchDao;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 赵岳宁 on 2017/5/1.
 */

@Repository
public class SearchDaoImpl implements SearchDao {

    @Autowired
    private SolrServer solrServer ;

    @Override
    public SearchResult search(SolrQuery query) throws SolrServerException {
        QueryResponse response = solrServer.query(query);
        SolrDocumentList results = response.getResults();
        List<SearchItemBean> itemBeanList = new ArrayList<>();
        for (SolrDocument document :
                results) {
            SearchItemBean itemBean = new SearchItemBean();
            itemBean.setId((String) document.get("id"));
            itemBean.setCategory_name((String) document.get("item_category_name"));
            itemBean.setImage((String) document.get("item_image"));
            itemBean.setPrice((long) document.get("item_price"));
            itemBean.setSell_point((String) document.get("item_sell_point"));
            //取高亮显示
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            List<String> list = highlighting.get(document.get("id")).get("item_title");
            String itemTitle = "";
            //有高亮显示的内容时。
            if (list != null && list.size() > 0) {
                itemTitle = list.get(0);
            } else {
                itemTitle = (String) document.get("item_title");
            }
            itemBean.setTitle(itemTitle);
            //添加到商品列表
            itemBeanList.add(itemBean);
        }
        SearchResult result = new SearchResult();
        result.setItemList(itemBeanList);
        result.setRecordCount(results.getNumFound());

        return result;
    }
}
